import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

import {
  getAddressListAPI,
  deleteAddressAPI,
  addAddressAPI,
  updateAddressAPI,
  getAddressDetailAPI,
} from '@/services/address'
import type { AddressParams, AddressItem } from '@/types/address'

export const useAddressStore = defineStore('address', () => {
  /* 地址列表 */
  const addressList = ref<AddressItem[]>([])

  /**订单收货地址 */
  const orderAddress = ref<AddressItem>()

  /**获取收货地址列表 */
  const getAddressList = async () => {
    const res = await getAddressListAPI()
    addressList.value = res.result
  }

  /**获取收货地址详情
   * @param {string} id 收货地址id
   */
  const getAddressDetail = async (id: string) => {
    const res = await getAddressDetailAPI(id)
    return res
  }

  /**新建收货地址
   * @param { AddressParams } data 添加收货地址参数
   */
  const addAddress = async (data: AddressParams) => {
    const res = await addAddressAPI(data)
    return res
  }

  /**修改收货地址
   * @param { string } id 修改收货地址id
   * @param { AddressParams } data 修改收货地址参数
   */
  const updateAddress = async (id: string, data: AddressParams) => {
    const res = await updateAddressAPI(id, data)
    return res
  }

  /**删除收货地址
   * @param {string } id 收货地址id
   */
  const deleteAddress = async (id: string) => {
    const res = await deleteAddressAPI(id)
    return res
  }
  /**选择订单收货地址 */
  const selectOrderAddress = (id: string) => {
    orderAddress.value = addressList.value.find((item) => item.id === id)
  }

  return {
    addressList,
    orderAddress,
    getAddressList,
    getAddressDetail,
    addAddress,
    updateAddress,
    deleteAddress,
    selectOrderAddress,
  }
})
